package com.itany.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MissChen
 * @date 2024年03月21日 15:56
 */
public class Test04_基本操作 {
    public static void main(String[] args) throws DataAccessException {
        // User user = new User("huahua3", "123", "15898745689", "南京");
        // insertUser(user);

        // deleteById(7);
        // User user = new User(4, "haha", "1234", "15898745111", "shanghai");
        // updateUser(user);

        // User user = selectById(4);
        // System.out.println(user);

        List<User> users=findAll();
        System.out.println(users);
}

    /**
     * 添加用户
     * @param user
     */
    public static void insertUser(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {

            //获得连接
            conn = JDBCUtil.getConnection();

            //由于开发中SQL可能比较长，一般情况可以使用StringBuffer进行sql拼接
            //可以提高代码的可读性，编写的时候SQL缺少空格的问题，每一行前后都留一个空格
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values ")
                    .append(" (?,?,?,?) ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());

            //执行DML操作
            int rows = ps.executeUpdate();

            System.out.println("插入成功~");


        } catch (DataAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

    //根据id删除，一个参数
    public static void deleteById(Integer id) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" delete from t_user ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            int rows = ps.executeUpdate();
            System.out.println(rows);
            System.out.println("删除成功");
        } catch (DataAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

    //修改用户，一个参数，User user
    public static void updateUser(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" update t_user  ")
                    .append(" set ")
                    .append(" username=?,")
                    .append(" password=?,")
                    .append(" phone=?,")
                    .append(" address=? ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            ps.setInt(5, user.getId());
            int rows = ps.executeUpdate();
            System.out.println("修改成功");
        } catch (DataAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }


    //根据id查询用户，一个参数
    public static User selectById(Integer id) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address  ")
                    .append(" from t_user ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);

            rs = ps.executeQuery();
            while (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
            }
            return user;
        } catch (DataAccessException e) {

            throw e;
        } catch (SQLException e) {

            throw new DataAccessException("数据库访问异常");
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

    //查询所有用户
    public static List<User> findAll() throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();

        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address  ")
                    .append(" from t_user ")
                    .toString();
            ps = conn.prepareStatement(sql);

            rs = ps.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }
            return users;
        } catch (DataAccessException e) {

            throw e;
        } catch (SQLException e) {

            throw new DataAccessException("数据库访问异常");
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

}
